package com.feeyo.groundservice.zxing

import android.content.res.ColorStateList
import android.graphics.Color
import android.os.Bundle
import android.view.Gravity
import android.view.KeyEvent
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.graphics.toColorInt
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.ScreenUtils
import com.feeyo.groundservice.base_util.FyLog
import com.feeyo.groundservice.base_util.getColor
import com.feeyo.groundservice.base_util.getPxFromResource
import com.feeyo.groundservice.zxing.constant.ZxingConstant
import com.feeyo.groundservice.zxing.databinding.ContinuousScanBinding
import com.google.zxing.BarcodeFormat
import com.google.zxing.ResultPoint
import com.google.zxing.client.android.BeepManager
import com.journeyapps.barcodescanner.BarcodeCallback
import com.journeyapps.barcodescanner.BarcodeResult
import com.journeyapps.barcodescanner.Size
import com.therouter.TheRouter
import com.therouter.router.Autowired

/**
 *作者：70893 on 2025-07-31
 *描述：
 */
internal abstract class BaseZxingActivity : AppCompatActivity() {

    protected val TAG = "扫码格式"
    protected lateinit var beepManager: BeepManager
    protected var lastText: String = ""
    private var openFlashLight = false

    protected var prompt = "请将二维码或条形码放入框内，即可自动扫描"

    protected lateinit var binding: ContinuousScanBinding

    @Autowired(name = ZxingConstant.TITLE)
    @JvmField
    var title: String? = null

    @Autowired(name = ZxingConstant.CALLBACK)
    @JvmField
    var scanCallback: ScanCodeListener? = null


    internal val callback: BarcodeCallback = object : BarcodeCallback {
        override fun barcodeResult(result: BarcodeResult) {
            if (result.text == null || result.text == lastText) {
                // 如果扫描结果为空或者重复，不处理
                return
            }
            lastText = result.text
            beepManager.playBeepSoundAndVibrate()

            val format = result.barcodeFormat
            FyLog.e(TAG, format.name)

            if (!validateCodeFormat(result)) return

            dataCallback(format.name)
        }

        override fun possibleResultPoints(resultPoints: List<ResultPoint>) {}
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        TheRouter.inject(this)//参数自动注入
        BarUtils.setStatusBarColor(
            this, R.color.zxing_transparent.getColor(), true
        )
        BarUtils.setStatusBarLightMode(this, false)

        binding = ContinuousScanBinding.inflate(layoutInflater)
        setContentView(binding.root)

        beepManager = BeepManager(this)
        binding.barcodeScanner.setStatusText("")

        binding.backIv.setOnClickListener { finish() }
        binding.titleTv.text = title ?: intent.getStringExtra(ZxingConstant.TITLE) ?: "扫码"
        binding.titleLy.apply {
            (layoutParams as RelativeLayout.LayoutParams).topMargin = BarUtils.getStatusBarHeight()

        }

        //布局设置
        binding.barcodeScanner.apply {
            initializeFromIntent(intent)

        }
        //设置扫描框尺寸
        val width = ScreenUtils.getScreenWidth() * 0.8f
        binding.barcodeScanner.barcodeView.apply {
            framingRectSize = Size(width.toInt(), (width * 3 / 4).toInt())
        }
        //设置遮罩层颜色
        binding.barcodeScanner.viewFinder.apply {
            setMaskColor("#A0000000".toColorInt())
        }
        //添加说明
        binding.root.apply {
            addView(TextView(context).apply {
                layoutParams = RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.MATCH_PARENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT
                ).apply {
                    topMargin =
                        (ScreenUtils.getAppScreenHeight() / 2 + width * 3 / 7).toInt()
                }
                gravity = Gravity.CENTER
                text = prompt
                setTextColor(R.color.white.getColor())
            })

            //添加闪光灯按钮
            addView(ImageView(context).apply {
                layoutParams = RelativeLayout.LayoutParams(
                    R.dimen.d30.getPxFromResource(),
                    R.dimen.d30.getPxFromResource()
                ).apply {
                    addRule(RelativeLayout.CENTER_HORIZONTAL)
                    topMargin =
                        (ScreenUtils.getAppScreenHeight() / 2 + width * 3 / 8 - R.dimen.d30.getPxFromResource()).toInt()
                }
                setOnClickListener {
                    if (!openFlashLight)
                        binding.barcodeScanner.setTorchOn()
                    else
                        binding.barcodeScanner.setTorchOff()

                    openFlashLight = !openFlashLight
                    if (openFlashLight)
                        imageTintList = ColorStateList.valueOf(Color.GREEN)
                    else
                        imageTintList = ColorStateList.valueOf(Color.WHITE)
                }
                setImageResource(R.drawable.icon_flash_light)

            })
        }

        differentSettings()
    }


    override fun onResume() {
        super.onResume()
        binding.barcodeScanner.resume()
    }

    override fun onPause() {
        super.onPause()
        binding.barcodeScanner.pause()
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        return binding.barcodeScanner.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event)
    }

    abstract fun differentSettings()

    abstract fun validateCodeFormat(result: BarcodeResult): Boolean

    abstract fun dataCallback(format:String)
}